import PhyWorld from "./fight/phyworld";
import SGui from "../framework/gui/sgui";
import RescacheMgr from "../framework/inc/rescachemgr";
import { func_hook } from "../framework/extend/jsex";
var CannonDebugRenderer = require("../framework/threeex/CannonDebugRenderer");
import { DEBUG } from "../relconf";


const TOUCH_EVENT = [
    "touchstart",
    "touchend",
    "touchmove",
    "touchcancel"
]

export default class EditorStage {
    constructor(sceneobj, camera, renderer, hudcamera) {
        this._scene = sceneobj;
        this._camera = camera;
        this._render = renderer;
        this._hud_camera = hudcamera;
        this._gameworld = undefined;

        this._itouch = false;

        // this._init_base();
        // this._init_fight();
        // this._test_performance()
    }

    /* ================================ */

    _init_base() {
        //touch 
        let self = this;
        let dom = this._render.domElement;
        for (const key in TOUCH_EVENT) {
            if (TOUCH_EVENT.hasOwnProperty(key)) {
                const element = TOUCH_EVENT[key];
                const evtfunc = "_" + element
                if (typeof (self[evtfunc]) == "function") {
                    dom.addEventListener(element, (evt) => {
                        evt.preventDefault();
                        self[evtfunc](evt);
                        if (self._gameworld && !SGui.isMask()) {
                            func_hook(self._gameworld, evtfunc, evt);
                        }
                        SGui.chkTouchGUI(evt, this._hud_camera);
                    }, false)
                }
            }
        }
    }

    _init_fight() {
        console.log("showing phyworld...");
        
        // RescacheMgr.getInstance().preload(() => {
        //     let phyworld = PhyWorld.getWorld(this._scene, this._camera);
        //     this._gameworld = phyworld;

        if (DEBUG) this._init_debug();
        // })
    }

    _init_debug() {
        if (this._gameworld) {
            let cannon_helper = new CannonDebugRenderer(this._scene, this._gameworld.world);
            this._cannon_helper = cannon_helper;
        }

        let axes_helper = new THREE.AxesHelper(100);
        this._scene.add(axes_helper);

        let grid_helper = new THREE.GridHelper(100, 100, 0xf0f0f0, 0xffffff);
        this._scene.add(grid_helper);
    }

    /* ============================== */
    _touchstart(evt) {
    }

    _touchmove(evt) {
    }

    _touchend(evt) {
    }

    _touchcancel(evt) {
    }

    update() {
        // phyworld
        if (this._gameworld && this._gameworld.world) {
            this._gameworld.world.step(1 / 30);
            this._gameworld.update();
        }
        //phyworld-helper
        if (DEBUG && this._cannon_helper) {
            this._cannon_helper.update();
        }
    }
}